<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>笑话机</title>

    <link href="style/joker.css" rel="stylesheet">
  </head>

  <body>
    <div>
      <label for="customname">输入自定义名字：</label>
      <input id="customname" type="text" placeholder="李雷">
    </div>
    <div>
      <label for="metric">公制</label><input id="metric" type="radio" name="measure" value="metric" checked>
      <label for="american">美制</label><input id="american" type="radio" name="measure" value="american">
    </div>
    <div>
      <button class="randomize">生成随机笑话</button>
    </div>
    <!-- 鸣谢：Willy Aguirre 提供的测试代码 -->
    <p class="story"></p>
  </body>

  <script>

    function randomValueFromArray(array) {
      return array[Math.floor(Math.random() * array.length)];
    }
    
    const randomize = document.querySelector('.randomize');
    randomize.addEventListener('click', result);
    const story = document.querySelector('.story');
    const insertX  = ['怪兽威利','大老爹','圣诞老人'];
    const insertY  = ['肯德基','迪士尼乐园','白宫'];
    const insertZ  = ['自燃了','在人行道化成了一坨泥','变成一条鼻涕虫爬走了'];
    let weight = Math.round(300);
    let temperature = Math.round(94);
    let weightType='华氏度';
    let temperatureType='磅';
    function result() {
      const customName = document.getElementById('customname');
      let name ='';
      if(customName.value !== '') {
        name = customName.value;
      }
      if(document.getElementById("american").checked) {
        weight = Math.round(300);
        temperature = Math.round(94);
        weightType='华氏度';
        temperatureType='磅';
      }else{
        weight = Math.round(130);
        temperature = Math.round(34);
        weightType='公斤';
        temperatureType='摄氏度';
      }
      let xItem ='';
      if(name!==''){
        xItem = name;
      }else{
        xItem = randomValueFromArray(insertX);
      }
      let yItem  = randomValueFromArray(insertY);
      let zItem = randomValueFromArray(insertZ);
      story.textContent = `今天气温 ${weight} ${weightType},${xItem}出去遛弯。当走到${yItem}门前时，突然就${zItem}。人们都惊呆了，李雷全程目睹但并没有慌，因为${xItem}是一个 ${temperature} ${temperatureType}的胖子，天气又辣么热。`;
      story.style.visibility = 'visible';
    }

    </script>
</html>